package com.cyc.quick.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyc.quick.pojo.entity.SysUser;
import com.cyc.quick.service.ISysUserService;
import com.cyc.quick.exception.ProjectException;
import com.cyc.quick.pojo.vo.UserInfoVO;
import com.cyc.quick.util.ApiResult;
import com.cyc.quick.util.BeanHelper;
import com.cyc.quick.pojo.vo.LoginReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenyunchang
 * @since 2021-01-19
 */
@RestController
@RequestMapping
@Api(tags = "登陆相关接口")
@Slf4j
public class LoginController {

    @Autowired
    private ISysUserService sysUserService;

    @ApiOperation("登陆")
    @PostMapping("/login")
    public ApiResult<UserInfoVO> list(@Validated @RequestBody LoginReq loginReq, HttpServletRequest request, HttpServletResponse response, BindingResult result) {
        if (result.hasErrors()) {
            //将错误拼接成字符串
            String msg = result.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
            throw new ProjectException("400", msg);
        }
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getPhone, loginReq.getPhone());
        SysUser userDb = sysUserService.getOne(lambdaQueryWrapper);
        if (userDb == null || !Objects.equals(loginReq.getPassword(), userDb.getPassword())) {
            throw new ProjectException("400", "用户名或密码错误");
        }
        HttpSession session = request.getSession();
        //将登录信息写入session中
        Object userInfo = session.getAttribute("userInfo"+loginReq.getPhone());
        UserInfoVO userInfoVO = BeanHelper.copyProperties(userDb, UserInfoVO.class);
        //设置一小时后过期
        session.setMaxInactiveInterval(3600);
        if (userInfo == null) {
            session.setAttribute("userInfo" + loginReq.getPhone(), userInfoVO);
        }
        return ApiResult.success(userInfoVO);
    }
}

